package logic

import (
	"context"
	"errors"
	"fmt"
	"iot-golangzero/helper"
	"iot-golangzero/models"

	"iot-golangzero/user/internal/svc"
	"iot-golangzero/user/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserLoginLogic) UserLogin(req *types.UserLoginRequest) (resp *types.UserLoginResponse, err error) {
	// todo: add your logic here and delete this line
	resp = new(types.UserLoginResponse)
	//业务代码.....
	ub := models.UserBasic{}
	err = l.svcCtx.DB.Where("username = ? and password = ?", req.Username, req.Password).First(&ub).Error
	fmt.Println(ub)
	if err != nil {
		fmt.Println(err)
		logx.Error("[DB ERROR ]: ", err)
		err = errors.New("用户名或密码不正确")
		return
	}

	token, err := helper.GenerateToken(ub.ID, ub.Identity, ub.Username, 3600*24*30)
	if err != nil {
		fmt.Println(err)
		logx.Error("[DB ERROR ]: ", err)
		err = errors.New("用户名或密码不正确222222")
		return
	}
	resp.Token = token
	fmt.Println(">>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>>", req.Password+req.Username)
	return
}
